<script setup>
import { useUserStore } from '@/stores/user';
import { EiInfo } from '@eplat/ei';
import api4j from '@/api/example';
import { Dialog, Toast } from 'vant';
import JWeixin from 'weixin-js-sdk';
import { queryUrlParam } from '@/utils/tools';
const router = useRouter();
const user = useUserStore();
const pos = ref('');
const content = ref('');

// 授权
JWeixin.config({
  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
  appId: api4j.APPID, // 必填，公众号的唯一标识
  timestamp: '', // 必填，生成签名的时间戳
  nonceStr: '', // 必填，生成签名的随机串
  signature: '', // 必填，签名
  jsApiList: [] // 必填，需要使用的JS接口列表
});
JWeixin.ready(async () => {
  // 获取用户code
  const code = queryUrlParam('code');
  // 没有授权code
  if (code == null) {
    // Toast('授权失败');
    // 跳转到授权页面
    window.location.href =
      'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
      api4j.APPID +
      '&redirect_uri=https%3A%2F%2F' +
      api4j.SERVER_DOMAIN +
      '%2F%23%2FWX%2FKH%2FWXKH04&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
  } else {
    // 本地没有token新授权
    if (user.getToken == '' || user.getToken == undefined) {
      // Toast('正在授权');
      const postEiInfo = new EiInfo();
      postEiInfo.set('code', code);
      // 通过code获取用户信息
      await api4j.wxLogin(postEiInfo).then((res) => {
        // 如果授权无效 重新授权
        if (res.status !== 1) {
          // Toast(res.msg);
          window.location.href =
            'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
            api4j.APPID +
            '&redirect_uri=https%3A%2F%2F' +
            api4j.SERVER_DOMAIN +
            '%2F%23%2FWX%2FKH%2FWXKH04&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
          return;
        }
        // Toast(res.msg);
        // token info存放本地
        user.setUserInfo(
          res.extAttr.token,
          res.extAttr.userInfo.attrs.headimgurl,
          res.extAttr.userInfo.attrs.nickname
        );
        user.setUserNameTel(res.extAttr.username, res.extAttr.phone);

        onLoad();
      });
    }
  }
});

const submit = async () => {
  if (user.getUsername == undefined || user.getUsername == '') {
    Toast('未登录，请重新登录');
    return;
  }
  if (pos.value == '') {
    Toast('请输入意见地址');
    return;
  }
  if (content.value == '') {
    Toast('请输入意见内容');
    return;
  }

  Dialog.confirm({
    title: '意见',
    message: '确认发表意见吗?'
  })
    .then(async () => {
      const postEiInfo = new EiInfo();
      postEiInfo.set('pos', pos.value);
      postEiInfo.set('name', user.getUsername);
      postEiInfo.set('content', content.value);
      postEiInfo.set('tel', user.getPhone);
      postEiInfo.set('fileList', '无图片');
      if (!fileList.value.length == 0) {
        // // 记录开始时间
        // const startTime = performance.now();
        // 批量
        const files1 = [];
        const batchSize = 1000; // 设置适当的批次大小
        for (let i = 0; i < fileList.value.length; i += batchSize) {
          const batch = fileList.value
            .slice(i, i + batchSize)
            .map((item) => ({ file: item.content }));
          files1.push(...batch);
        }

        postEiInfo.set('fileList', JSON.stringify(files1));
        setInterval(() => {
          time.value += 1;
        }, 1000);
      }

      // // 记录结束时间
      // const endTime = performance.now();
      //
      // // 计算执行时间（以毫秒为单位）
      // const executionTime = endTime - startTime;
      //
      // console.log(`执行时间：${executionTime} 毫秒`);

      await api4j.RCRM0103_addTs(postEiInfo).then((res) => {
        if (res.status == 1) {
          Toast('新增成功');
          router.replace('/WX/KH/WXKH03');
        }
      });
    })
    .catch(() => {
      // on cancel
    });
};
const time = ref(0);
const fileList = ref([]);
</script>
<template>
  <div>
    <div
      style="
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        background: #4b75e5;
        height: 65px;
        color: white;
        z-index: 1000;
      "
    >
      <div style="font-size: 20px; padding-top: 20px; text-align: center">我的意见</div>
      <van-button
        to="/WX/KH/WXKH03"
        style="
          background-color: #4b75e5;
          color: white;
          display: flex;
          flex-direction: column;
          align-items: center;
          border: 1px solid #4b75e5;
          margin-top: -32px;
          margin-left: 20px;
        "
      >
        <img
          src="@/assets/tb166.svg"
          style="width: 35px; height: 35px; margin-top: 3px; margin-left: -20px"
          alt=""
        />
      </van-button>
    </div>
    <van-form class="form-card" style="margin-top: 75px" @submit="submit">
      <van-cell-group class="form-cell-group" inset>
        <van-field v-model="user.getUsername" label="姓名：" readonly required />
        <van-field v-model="user.getPhone" label="电话：" readonly required />
        <van-field
          v-model="pos"
          label="意见地址："
          type="textarea"
          placeholder="请输入被意见人地址"
          required
        />
        <van-field
          v-model="content"
          label="内容："
          type="textarea"
          placeholder="请输入内容"
          required
        />

        <van-cell class="item-value group1">
          <div class="group1">
            <div class="titles">附件上传: <span style="color: red">(图片大小不超过5M)</span></div>
          </div>

          <van-uploader v-model="fileList" multiple />
          <div v-if="fileList.length!=0" style="height: 10px">
            <van-progress color="#32CD32 " :percentage="time" />
          </div>
        </van-cell>
      </van-cell-group>
      <van-button
        round
        native-type="submit"
        style="background-color: #4b75e5; color: white; width: 90%; margin: 10px auto"
        block
        >保存</van-button
      >
    </van-form>
  </div>
</template>

<style lang="stylus" scoped>
.page-main

  .working-list
    .item1
      padding-top 0px
      padding-bottom 0px
    .title1
      color #003586
      font-weight bolder
      font-size 13px
    .titles
      color #161718
      font-weight bolder
      font-size 13px
    .titless
      color #161718
      font-weight bolder
      font-size 17px
    .title2
      color #808080
      font-size 13px
    padding 4px
    margin-bottom 48px
    .van-tag
      margin-left 5px
      font-size 12px
      padding 5px
    .btn1
      background-color #038008
      border-radius 5px
      margin-left 5px
    .btn0
      background-color #ff8d1a
      border-radius 5px
      margin-left 5px
    .class1
      background-color #99bcf1
      border-radius 5px
    .class2
      background-color #f19999
      border-radius 5px
    .class3
      background-color #99a6f1
      border-radius 5px
    .card-item
      margin 8px
      background-color white

      .item-value
        display flex
        justify-content space-between
        overflow hidden
        text-overflow ellipsis
        word-break keep-all
        white-space nowrap
        background-color transparent
        .group1
          display flex
          flex-direction row
          justify-content space-between

  .bottom-buttons
    position fixed
    bottom 12px
    left auto
    width 100%
    max-width var(--max-width)
</style>
